#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->progressBar->hide();

    setupActions();

    MediaFactory mf;
    movieList_ = mf.getData();
}

MainWindow::~MainWindow()
{
    delete ui;
}

///
/// An event to stop the scanning process
void MainWindow::scan()
{
    QSettings settings(CONFIG_FILE, QSettings::IniFormat);
    QString directoryPath = settings.value("library/directory").toString();
    if (!QFile::exists(directoryPath))
        directoryPath = QFileDialog::getExistingDirectory(this, tr("Open Video Directory"),
                                                              QDir::homePath());
    settings.setValue("library/directory", directoryPath);

    DataCollector dc(QDir(directoryPath), this);
    dc.run();

    const MovieList &fileList = dc.getFileList();
    QVector<QSharedPointer<Movie> >::const_iterator it;

    for (it = fileList.constBegin(); it != fileList.constEnd(); ++it) {
        //qDebug() << "Parse: " << (*it).toLocal8Bit().constData();
        QString filePath((*it)->getFilePath());
        QString title((*it)->getTitle());
        QString id = (*it)->getId().toString();

        int rowCount = ui->videoTableWidget->rowCount();
        int row = rowCount+1;

        ui->videoTableWidget->setRowCount(row);

        QTableWidgetItem *idItem = new QTableWidgetItem(id);
        ui->videoTableWidget->setItem(rowCount, 0, idItem);

        QTableWidgetItem *titleItem = new QTableWidgetItem(title);
        ui->videoTableWidget->setItem(rowCount, 1, titleItem);

        QTableWidgetItem *pathItem = new QTableWidgetItem(filePath);
        ui->videoTableWidget->setItem(rowCount, 2, pathItem);
    }
}

///
/// Refreshs the movie list table
void MainWindow::refresh()
{
    ui->videoTableWidget->clear();
    ui->videoTableWidget->setRowCount(0);

    QVector<QSharedPointer<Movie> >::iterator it;
    for (it = movieList_.begin(); it != movieList_.end(); ++it) {
        QString filePath((*it)->getFilePath());
        QString title((*it)->getTitle());
        QString id = (*it)->getId().toString();

        int rowCount = ui->videoTableWidget->rowCount();
        int row = rowCount+1;

        ui->videoTableWidget->setRowCount(row);

        QTableWidgetItem *idItem = new QTableWidgetItem(id);
        ui->videoTableWidget->setItem(rowCount, 0, idItem);

        QTableWidgetItem *titleItem = new QTableWidgetItem(title);
        ui->videoTableWidget->setItem(rowCount, 1, titleItem);

        QTableWidgetItem *pathItem = new QTableWidgetItem(filePath);
        ui->videoTableWidget->setItem(rowCount, 2, pathItem);
    }
}

///
/// Online database lookup
void MainWindow::lookup()
{
    int rowCount = ui->videoTableWidget->rowCount();
    tmdb_ = new Tmdb(this);

    ui->progressBar->setMinimum(0);
    ui->progressBar->setMaximum(rowCount-1);
    ui->progressBar->show();

    for (int i = 0; i < rowCount; ++i) {
        QTableWidgetItem *item = ui->videoTableWidget->item(i, 0);
        int id = item->text().toInt();
        Movie *tMovie = MediaFactory::movie(id);
        tmdb_->lookupMovie(tMovie);
        Tmdb::results res = tmdb_->result();
        if (res.count() == 1) {
            tMovie->setTitle(res.at(0).title);
            tMovie->setTmdbId(res.at(0).tmdb_id);
            tMovie->setCover(res.at(0).cover);
        }
        tMovie->saveToDatabase();
        delete tMovie;
        ui->progressBar->setValue(i);
    }
    ui->progressBar->hide();
}

///
/// Loads the movie details
void MainWindow::loadDetails()
{
    int row = ui->videoTableWidget->currentRow();

    QTableWidgetItem *item = ui->videoTableWidget->item(row, 1);
    QString title = item->text();

    QSqlQuery query("SELECT i.image FROM images AS i "
                    "JOIN movies AS m "
                    "ON (i.ID = m.IMAGE_ID) "
                    "WHERE m.title='"+title+"'");
    while (query.next()) {
        QPixmap pixmap;
        pixmap.loadFromData(query.value(0).toByteArray());
        ui->coverLabel->setPixmap(pixmap);
    }
}

///
/// Loads the settings window
void MainWindow::loadSettingsDialog()
{
    Settings s;
    s.exec();
}

///
/// Initialize all actions
void MainWindow::setupActions()
{
    connect(ui->actionScan, SIGNAL(triggered()), this, SLOT(scan()));
    connect(ui->actionRefresh, SIGNAL(triggered()), this, SLOT(refresh()));
    connect(ui->actionLookup, SIGNAL(triggered()), this, SLOT(lookup()));
    connect(ui->videoTableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(loadDetails()));
    connect(ui->actionOptions, SIGNAL(triggered()), this, SLOT(loadSettingsDialog()));
}
